import { getFrontUploadSign } from "../../../service/config"
import { updatePayInfo, updateMyPersonalInfo, cancelBindCompany } from "../../../service/user_service"
import { chooseAndUploadQiniuActicon, chooseAndUploadOSSActicon } from "../../../service/upload_service"
import {
  editUserInfo
} from "../../../service/jb_mine_service"
import {
  getPersonReq
} from "../../../service/jb_activity_service"
import debounce from "../../../tools/debounce"
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    themeStyle: "",
    formData: {
      nickname: "",
      avatar: "",
      vipName: "",
      level: '',
      phone: "",
    },
    uploadData: {},
    roleType: 1,
    //支付信息
    payInfoData: {
      "bankAccount": "",//银行账户
      "bankName": "",//银行名称

      "cardBack": "",//身份证反面
      "cardFront": "",//身份证正面
      "openBank": "",//开户行
      "openName": "",//开户名
    },
    personData: {

    },
    isUpdateAvatar: false,
    isUpdateNickName: false,
    isUpdateName: false,
    isUpdateWeChat: false,

    isEditPayInfo: false,
    isCheckOpen: false,
    vipMap: app.globalData.vipLevelMap,
    aliAccount: "",
    authInfo: {},
    inviteCode: '',//邀请码
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // this.setData({
    //   isCheckOpen: app.globalData.isCheckOpen
    // })
    // this.setData({
    //   'formData.avatar': app.globalData.avatar,
    //   'formData.nickName': app.globalData.nickName || "",
    //   'formData.roleName': app.globalData.roleName || "",
    //   'formData.phone': app.globalData.phone || "",
    //   'formData.companyName': app.globalData.companyName || "",
    //   'formData.companyNumber': app.globalData.companyNumber || "",
    //   'formData.name': app.globalData.name || "",
    //   'formData.weChat': app.globalData.weChat || "",
    //   roleType: app.globalData.roleType || 1
    // })
    this.setData({
      formData: app.globalData.userInfo,
    })
    // console.log('JJLog:userInfo:' + app.globalData.userId);

    this.setData({
      payInfoData: app.globalData.userPayInfo,
      isEditPayInfo: app.globalData.userPayInfo.isEdit
    })
    this.getFrontUploadSign();
    this.getPersonAction();
    this.getInviteCode();
  },
  getInviteCode() {
    this.setData({
      inviteCode: this.encryptNumber(parseInt(app.globalData.userId)).toUpperCase()
    })
  },
  copyInviteCode() {
    wx.setClipboardData({
      data: this.data.inviteCode,
      success: function (res) {
        wx.showToast({
          title: '复制邀请码成功'
        })
      },
      fail: function (err) {
        wx.showToast({
          title: '复制失败',
          icon: "none"
        })
      }
    })
  },
  //加密方法
  encryptNumber(num) {
    // 确保数字在合理范围内
    if (num < 0 || num >= Math.pow(36, 6)) {
      throw new Error("数字超出可编码范围");
    }

    const charSet = 'abcdefghijklmnopqrstuvwxyz0123456789';
    let encryptedStr = '';

    // 循环处理直到数字为0
    while (num > 0) {
      let remainder = num % 36; // 使用36进制（26个字母+10个数字）
      encryptedStr = charSet[remainder] + encryptedStr;
      num = Math.floor(num / 36);
    }

    // 如果长度不足6位，在前面补充字符。这里以'a'为例，实际可根据需求调整
    while (encryptedStr.length < 6) {
      encryptedStr = 'a' + encryptedStr;
    }

    return encryptedStr.substring(0, 6); // 确保最终长度不超过6位
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.themeStyle) {
      this.setData({
        themeStyle: app.globalData.themeStyle
      })
    }
    if (app.globalData.selectBankName != "") {
      this.setData({
        'payInfoData.bankName': app.globalData.selectBankName
      })
      app.globalData.selectBankName = "";
    }
    if (app.globalData.cropperAvatar) {
      this.setData({
        'formData.avatar': app.globalData.cropperAvatar,
        isUpdateAvatar: true,
        'personData.avatar': app.globalData.cropperAvatar
      })
      app.globalData.cropperAvatar = "";

    }
    if (app.globalData.userInfo.aliAccount) {
      this.setData({
        aliAccount: app.globalData.userInfo.aliAccount,
      })
    }
  },
  //去编辑或者修改支付宝信息
  pushToAlPay() {
    wx.navigateTo({
      url: '/featurePackage/pages/bindAiPay/bindAiPay',
    })
  },
  //去认证
  pushToAuth() {
    let isAuth = this.data.authInfo.phone ? '1' : '0'

    wx.navigateTo({
      url: '/featurePackage/pages/bindPerson/bindPerson?isAuth=' + isAuth,
    })
  },
  //去修改手机号
  changeUserPhone() {
    wx.navigateTo({
      url: '/featurePackage/pages/changePhone/changePhone',
    })
  },
  //重新授权微信头像:
  getUserAuthAction() {
    wx.navigateTo({
      url: '/formPackage/pages/cropperAvatar/cropperAvatar',
    })
    // chooseAndUploadOSSActicon('avatar').then(res => {
    //   console.log("JJLog:图片上传成功:" + JSON.stringify(res));
    //   wx.showToast({
    //     title: '上传成功',
    //   })



    //   this.setData({
    //     'formData.avatar': res.data.filename,
    //     isUpdateAvatar: true,
    //     'personData.avatar': res.data.filename
    //   })


    // }).catch(err => {
    //   console.error("JJLog:图片上传失败:" + JSON.stringify(err));
    //   wx.showToast({
    //     title: '上传头像失败',
    //     icon: "none"
    //   })
    // })

    // chooseAndUploadQiniuActicon("avatar")
    //   .then(imageRes => {

    //     console.log("JJLog:上传的头像地址是:" + imageRes.complateUrl);
    //     this.setData({
    //       'formData.avatar': imageRes.complateUrl,
    //       isUpdateAvatar: true,
    //       'personData.avatar': imageRes.complateUrl
    //     })
    //   }).catch(err => {

    //     console.log(err)
    //     wx.showToast({
    //       title: '上传头像失败',
    //       icon: "none"
    //     })
    //   })

  },
  //获取自己的认证信息
  getPersonAction() {
    getPersonReq().then(res => {
      if (res.code == 200) {
        if (res.data) {
          this.setData({
            authInfo: res.data
          })
        } else {
          this.setData({
            authInfo: {}
          })
        }
      }
    }).catch(err => {
      this.setData({
        authInfo: {}
      })
      console.error("JJLog:getPersonReq", err);
    })
  },
  //更新信息
  updatePayInfoAction() {
    let data = this.data.payInfoData;
    // if (!this.data.isEditPayInfo) {
    //   wx.showToast({
    //     title: '暂时无法更新结算信息',
    //     icon: "none"
    //   })
    // }
    // if (!data.bankName) {
    //   wx.showToast({
    //     title: '请选择银行',
    //     icon: "none"
    //   })
    // }
    // if (!data.bankAccount) {
    //   wx.showToast({
    //     title: '请输入银行卡号',
    //     icon: "none"
    //   })
    // }
    // if (!data.openName) {
    //   wx.showToast({
    //     title: '请输入开户名',
    //     icon: "none"
    //   })
    // }
    // if (!data.cardFront) {
    //   wx.showToast({
    //     title: '请上传身份证正面',
    //     icon: "none"
    //   })
    // }
    // if (!data.cardBack) {
    //   wx.showToast({
    //     title: '请上传身份证反面',
    //     icon: "none"
    //   })
    // }
    if (this.data.isEditPayInfo) {
      debounce(this.updatePayInfo);
    }
    if (this.data.isUpdateAvatar || this.data.isUpdateName ||
      this.data.isUpdateNickName || this.data.isUpdateWeChat
    ) {

      debounce(this.updateMyInfo);

    }


  },
  updatePayInfo() {
    // wx.showLoading();
    updatePayInfo(this.data.payInfoData).then(res => {
      // wx.hideLoading();
      if (res.code == 200) {
        wx.showToast({
          title: '更新成功',
          icon: "success"
        })
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/home/home',
          })
        }, 2000)
      }
    }).catch(err => {
      // wx.hideLoading();
      wx.showToast({
        title: err || "操作失败",
        icon: "none"
      })
      console.error("JJLog:updatePayInfo", err);
    })
  },

  updateMyInfo() {
    wx.showLoading();
    editUserInfo(this.data.formData).then(res => {
      wx.hideLoading();
      if (res.code == 200) {
        wx.showToast({
          title: '更新成功',
          icon: "success"
        })
        setTimeout(() => {
          wx.navigateBack();
        }, 2000)
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || "更新失败",
        icon: "none"
      })
      console.error("JJLog:editUserInfo", err);
    })
  },
  //更新TIM个人资料
  updateTimProfile(nickName, avatar) {
    // 修改个人标配资料
    let promise = app.globalData.tim.updateMyProfile({
      nick: nickName,
      avatar: avatar,
    });
    promise.then(imResponse => {
      // 更新资料成功
      console.log("JJLog:更新TIM个人资料成功===", imResponse);
    }).catch(imError => {
      console.warn('JJLog更新TIM个人资料失败:', imError); // 更新资料失败的相关信息
    });
  },
  onChooseAvatar(e) {
    let _this = this;
    console.log('JJLog:头像结果是：' + JSON.stringify(e));
    let imgUrl = e.detail.avatarUrl;
    let expandName = imgUrl.substring(imgUrl.length - 10, imgUrl.length)
    wx.showLoading({
      title: '图片上传中',
    })
    wx.uploadFile({
      url: "https://gc-jb.oss-cn-hangzhou.aliyuncs.com",
      filePath: imgUrl,
      name: 'file',
      formData: {
        'key': this.data.uploadData.dir + "/" + new Date().getTime() + expandName,
        policy: this.data.uploadData.policy,
        OSSAccessKeyId: this.data.uploadData.accessId,
        signature: this.data.uploadData.signature,
        callback: this.data.uploadData.callback,
      },

      success: function (res) {
        wx.hideLoading()
        console.log("JJLog:图片上传成功===：", res);
        console.log("JJLog:图片上传成功：" + JSON.stringify(res));

        let resultData = JSON.parse(res.data);
        _this.setData({
          'formData.avatar': resultData.data.filename,
          isUpdateAvatar: true,
          'personData.avatar': resultData.data.filename
        })
      },
      fail: function (res) {
        wx.hideLoading()
        wx.showToast({
          title: '上传图片失败',
          icon: "none"
        })
      }
    });
  },
  // 上传图片
  pushImgAction(e) {
    if (!this.data.isEditPayInfo) {
      return;
    }
    let type = e.detail.type;
    chooseAndUploadQiniuActicon('id').then(res => {
      console.log("JJLog:图片上传成功:" + JSON.stringify(res));
      wx.showToast({
        title: '上传成功',
      })
      if (type == "idFront") {
        this.setData({
          'payInfoData.cardFront': res.complateUrl
        })
      } else if (type == "idBack") {
        this.setData({
          'payInfoData.cardBack': res.complateUrl
        })
      } else if (type == "bussinessImg") {
        this.setData({
          'payInfoData.businessLicenseImg': res.complateUrl
        })
      }

    }).catch(err => {
      console.log("JJLog:图片上传失败:" + JSON.stringify(err));
      wx.showToast({
        title: '图片上传失败',
        icon: "none"
      })
    })
  },

  //输入绑定
  inputCellChange(e) {
    // console.log("JJLog:e==:" + JSON.stringify(e));
    let detail = e.detail;
    let changeItem = `formData.${detail.key}`;
    this.setData({
      [changeItem]: detail.value
    })
    if (detail.key == "nickname") {
      this.setData({
        isUpdateNickName: true,
        'personData.nickname': detail.value,
      })
    }
    if (detail.key == "name") {
      this.setData({
        isUpdateName: true,
        'personData.name': detail.value
      })
    }

  },
  inputPayChange(e) {
    let detail = e.detail;
    let changeItem = `payInfoData.${detail.key}`;
    this.setData({
      [changeItem]: detail.value
    })
  },

  //复制公司编号:
  copyWxChatAction(e) {
    let text = e.currentTarget.dataset.text;
    wx.setClipboardData({
      data: text,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '复制编号成功'
            })
          },
          fail: function (err) {
            wx.showToast({
              title: '复制失败',
              icon: "none"
            })
          }
        })
      }
    })

  },

  //去选择银行:
  selectBankAction() {
    if (!this.data.isEditPayInfo) {
      return;
    }
    wx.navigateTo({
      url: '/formPackage/pages/selectBankPage/selectBankPage',
    })
  },

  //解除公司绑定操作
  cancelBindAction() {
    if (this.data.roleType == 7) {
      wx.showModal({
        title: '提示',
        content: '是否解除和当前公司的绑定关系',
        confirmColor: "#FF0000",
        success: res => {
          if (res.confirm) {
            this.cancelBindCompany();
          }
        }
      })
    }


  },
  cancelBindCompany() {
    wx.showLoading();
    cancelBindCompany().then(res => {
      wx.hideLoading();
      if (res.code == 200) {
        wx.showToast({
          title: '解绑成功',
          icon: "success"
        })
        this.setData({
          'formData.companyName': "",
          'formData.companyNumber': "",
        })
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || "操作失败",
        icon: "none"
      })
      console.error("JJLog:cancelBindCompany", err);
    })
  },


  getFrontUploadSign() {
    getFrontUploadSign().then(res => {
      console.log("JJLog:获取到的图片签名是:" + JSON.stringify(res));
      if (res.code == 200) {

        wx.setStorageSync('ossHost', res.data.host);
        wx.setStorageSync('ossSignature', res.data.signature);
        wx.setStorageSync('ossPolicy', res.data.policy);
        wx.setStorageSync('ossAccessId', res.data.accessId);
        wx.setStorageSync('ossCallBack', res.data.callback);
        wx.setStorageSync('ossDir', res.data.dir);
        this.setData({
          uploadData: res.data
        })
      }
    }).catch(err => {
      console.error("JJLog:getFrontUploadSign", err);
    })
  },







})